import React, { useState } from 'react';
import { usePagination } from 'ahooks';
import UniversalPagination from '@/components/UniversalPagination';
import { Button, Card, Table, Popconfirm, Avatar, Space, message, Input, Tag, Tabs } from 'antd';
import { AppleOutlined, AndroidOutlined } from '@ant-design/icons';
import type { CurrentUser, UserProps } from './components/data';
import { GridContent } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import { getUserList, deleteUser } from '@/services/user';
import UpdateModalForm from './components/UpdateModalForm';
import CreateModalForm from './components/CreateModalForm';
import moment from 'moment';
import { AccountType, getRoleColor } from '@/configs/global';

const { TabPane } = Tabs;

const UserManager: React.FC<UserProps> = () => {
  const [refreshCount, setRefreshCount] = useState(0);
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    type: 'front',
  });
  const fetchList = async (params: {
    page: number;
    pageSize: number;
    keyword: string;
    type: string;
  }) => {
    try {
      const res = await getUserList({
        ...params,
      });
      if (res.success) {
        return {
          total: res.data.totalNum,
          list: res.data.list,
        };
      } else {
        return { total: 0, list: [] };
      }
    } catch (error) {
      return { total: 0, list: [] };
    }
  };

  const handleDelete = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      const res = await deleteUser({ id });
      hide();
      if (res.success) {
        setRefreshCount(refreshCount + 1);
        message.success('删除成功');
      } else {
        return false;
      }
      return true;
    } catch (error) {
      hide();
      return false;
    }
  };
  const columns: ProColumns<CurrentUser>[] = [
    {
      title: '用户名',
      dataIndex: 'username',
      ellipsis: true,
    },
    {
      title: '电话号码',
      dataIndex: 'phone_number',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '角色类型',
      dataIndex: 'role',
      render: (_) => {
        return <Tag color={getRoleColor(_)}>{AccountType[_]}</Tag>;
      },
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      hideInSearch: true,
      render: (_) => {
        return <Avatar src={_} />;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'CreatedAt',
      valueType: 'dateRange',
      hideInTable: true,
      render: (_) => {
        return _ && moment(_).format('YYYY-MM-DD');
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => {
        return (
          <Space>
            <UpdateModalForm formVals={record} setRefreshCount={setRefreshCount} />
            {record.ID && (
              <Popconfirm
                placement="top"
                title="确定删除嘛？"
                onCancel={() => handleDelete(record.ID)}
                cancelButtonProps={{ type: 'primary', danger: true }}
                okText="取消"
                cancelText="是的"
                okType="default"
              >
                <Button key="view" type="primary" danger>
                  删除
                </Button>
              </Popconfirm>
            )}
          </Space>
        );
      },
    },
  ];
  const handleTabChange = (key: string) => {
    setSearchParams({ ...searchParams, type: key });
  };
  const { data, loading, pagination } = usePagination(
    ({ current, pageSize }) => {
      return fetchList({
        page: current,
        pageSize,
        keyword: searchParams.keyword,
        type: searchParams.type,
      });
    },
    {
      refreshDeps: [searchParams, refreshCount],
    },
  );

  return (
    <GridContent>
      <Card bodyStyle={{ padding: '32px 24px' }}>
        <Space direction="vertical" size={32} style={{ width: '100%' }}>
          <Space direction="horizontal" size={32} style={{ width: '100%' }}>
            <Input.Search
              style={{ width: 300 }}
              size="large"
              allowClear
              placeholder="输入关键词搜索"
              onSearch={(val) => {
                setSearchParams({
                  ...searchParams,
                  keyword: val,
                });
              }}
            />
          </Space>
          <Tabs
            onChange={handleTabChange}
            tabBarStyle={{ margin: 0 }}
            defaultActiveKey="reception"
            centered
          >
            <TabPane
              tab={
                <span>
                  <AppleOutlined />
                  前台用户列表
                </span>
              }
              key="front"
            >
              <Card
                extra={<CreateModalForm setRefreshCount={setRefreshCount} />}
                bodyStyle={{
                  padding: 0,
                }}
              >
                <Table
                  loading={loading}
                  pagination={false}
                  dataSource={data?.list}
                  columns={columns}
                />
                <UniversalPagination pagination={pagination} total={data?.total} />
              </Card>
            </TabPane>
            <TabPane
              tab={
                <span>
                  <AndroidOutlined />
                  后台用户列表
                </span>
              }
              key="backstage"
            >
              <Card
                extra={<CreateModalForm setRefreshCount={setRefreshCount} />}
                bodyStyle={{
                  padding: 0,
                }}
              >
                <Table
                  loading={loading}
                  pagination={false}
                  dataSource={data?.list}
                  columns={columns}
                />
                <UniversalPagination pagination={pagination} total={data?.total} />
              </Card>
            </TabPane>
          </Tabs>
        </Space>
      </Card>
    </GridContent>
  );
};

export default UserManager;
